package com.xunlai.infra.permission.manager.sercurity;

import com.xunlai.infra.permission.common.constant.ExtendClaimsConstants;
import com.xunlai.infra.permission.common.security.TenantUser;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

import java.util.Optional;

/**
 * @author liang
 * @date 12/8/22 10:54 PM
 */
public class SpringSecurityAuditorAware implements AuditorAware<Long> {


    @Override
    public Optional<Long> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = null;
        if(authentication instanceof JwtAuthenticationToken jwtAuthenticationToken){
            id = jwtAuthenticationToken.getToken().getClaim(ExtendClaimsConstants.ID);
        } else if (authentication.getPrincipal() instanceof OAuth2AuthenticatedPrincipal principal) {
            id = principal.getAttribute(ExtendClaimsConstants.ID);
        } else if(authentication.getPrincipal() instanceof TenantUser principal){
            id = principal.getId();
        }
        return Optional.ofNullable(id == null ? null : Long.valueOf(id));
    }
}
